import { useState, useEffect } from 'react';
import { 
  Save, 
  X, 
  Check, 
  AlertTriangle, 
  RefreshCw,
  ArrowLeft,
  Info
} from 'lucide-react';
import { toast } from 'sonner';
import { 
  getAiMode, 
  setAiMode 
} from '@/lib/config';
import { 
  getApiKey, 
  saveApiKey,
  validateApiKeyFormat,
  getMaskedApiKey,
  hasValidApiKey
} from '@/lib/apiKeyStore';

interface ApiConfigModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function ApiConfigModal({ isOpen, onClose }: ApiConfigModalProps) {
  const [apiKey, setApiKey] = useState('');
  const [aiMode, setAiMode] = useState<'real' | 'mock'>('mock');
  const [isSaving, setIsSaving] = useState(false);
  const [testResult, setTestResult] = useState<'idle' | 'testing' | 'success' | 'error'>('idle');
  const [apiKeyError, setApiKeyError] = useState('');
  const [hasGlobalApiKey, setHasGlobalApiKey] = useState(false);
  
  // 从本地存储加载配置
useEffect(() => {
  if (isOpen) {
    // 检查是否有全局配置的API Key
    const globalApiKey = getApiKey();
    const localStorageApiKey = localStorage.getItem('zhihuipu_api_key') || '';
    
    // 设置状态 - 修复类型转换问题
    setApiKey(localStorageApiKey);
    setHasGlobalApiKey(Boolean(globalApiKey && globalApiKey !== localStorageApiKey));
    setAiMode(getAiMode());
    setTestResult('idle');
  }
}, [isOpen]);
  
  // 保存配置
  const handleSave = () => {
    setIsSaving(true);
    
    try {
      // 保存API Key
      if (apiKey.trim() !== '') {
        saveApiKey(apiKey.trim());
      }
      
      // 保存AI模式
      setAiMode(aiMode);
      
      // 显示成功提示
      toast('配置保存成功！');
      
      // 关闭模态框
      onClose();
    } catch (error) {
      toast('保存失败，请稍后再试');
      console.error('Failed to save API configuration:', error);
    } finally {
      setIsSaving(false);
    }
  };
  
  // 测试API连接
  const handleTestApi = async () => {
    // 优先使用表单中输入的API Key，如果没有则使用getApiKey()获取的（包括全局配置的）
    const apiKeyToTest = apiKey.trim() || getApiKey();
    
    if (!apiKeyToTest) {
      toast('请输入有效的API Key');
      return;
    }
    
    // 验证API Key格式
    if (!validateApiKeyFormat(apiKeyToTest)) {
      setApiKeyError('API Key格式不正确，请检查后重新输入');
      return;
    }
    
    setApiKeyError('');
    setTestResult('testing');
  
    try {
      const response = await fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKeyToTest}`
        },
         body: JSON.stringify({
          model: 'glm-4',
          messages: [
            { role: 'user', content: '你好' }
          ],
          max_tokens: 50,
          temperature: 0.7
        })
      });
      
      if (response.ok) {
        const data = await response.json();
        if (data.choices && data.choices.length > 0) {
          setTestResult('success');
          toast('API连接成功！');
        } else {
          setTestResult('error');
          toast('API返回异常，请检查API Key是否正确');
        }
      } else {
        const errorData = await response.json();
        setTestResult('error');
        toast(`API连接失败: ${errorData.error?.message || '未知错误'}`);
      }
    } catch (error) {
      setTestResult('error');
      toast('网络连接失败，请检查您的网络设置');
      console.error('API test failed:', error);
    }
  };
  
  // 如果模态框未打开，不渲染任何内容
  if (!isOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl border border-pink-100 shadow-lg w-full max-w-md">
        {/* 头部 */}
        <div className="flex justify-between items-center p-5 border-b border-pink-100">
          <h3 className="text-lg font-bold text-gray-800 flex items-center">
            <span className="text-xl mr-2">🔑</span>
            智谱AI API配置
          </h3>
          <button 
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100"
          >
            <X size={20} />
          </button>
        </div>
        
        {/* 内容 */}
        <div className="p-5 space-y-4">
          {/* 模式选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-500 mb-2">
              AI 模式
            </label>
            <div className="flex space-x-3">
              <label className="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:border-pink-300 transition-colors flex-1">
                <input
                  type="radio"
                  name="aiMode"
                  value="real"
                  checked={aiMode === 'real'}
                  onChange={() => setAiMode('real')}
                  className="w-4 h-4 text-pink-500 focus:ring-pink-400 border-gray-300 rounded"
                />
                <span className="ml-2 text-gray-700">真实API</span>
              </label>
              <label className="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:border-pink-300 transition-colors flex-1">
                <input
                  type="radio"
                  name="aiMode"
                  value="mock"
                  checked={aiMode === 'mock'}
                  onChange={() => setAiMode('mock')}
                  className="w-4 h-4 text-pink-500 focus:ring-pink-400 border-gray-300 rounded"
                />
                <span className="ml-2 text-gray-700">模拟模式</span>
              </label>
            </div>
          </div>
          
           {/* API Key输入 */}
          <div>
            <label className="block text-sm font-medium text-gray-500 mb-2">
              API Key
              <span className="ml-1 text-red-500">*</span>
              {aiMode === 'real' && (
                <span className="text-xs text-gray-400 ml-2">(在真实模式下必须填写)</span>
              )}
            </label>
            <div className="relative">
              <input
                type="password"
                value={apiKey}
                onChange={(e) => setApiKey(e.target.value)}
                placeholder="请输入您的智谱AI API Key"
                className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-400 text-gray-800"
                 disabled={aiMode === 'mock'}
              />
              {apiKeyError && aiMode === 'real' && (
                <p className="text-red-500 text-xs mt-1">{apiKeyError}</p>
              )}
              {hasGlobalApiKey && (
                <div className="mt-1 flex items-center text-xs text-green-500">
                  <Info size={12} className="mr-1" />
                  已检测到全局配置的API Key: {getMaskedApiKey()}
                </div>
              )}
              {aiMode === 'real' && (
                <button 
                  onClick={handleTestApi}
                  disabled={testResult === 'testing'}
                  className="absolute right-2 top-1/2 transform -translate-y-1/2 p-1.5 bg-gray-100 rounded-lg text-gray-500 hover:bg-gray-200 transition-colors"
                  title="测试API连接"
                >
                  {testResult === 'testing' ? (
                    <RefreshCw size={18} className="animate-spin" />
                  ) : testResult === 'success' ? (
                    <Check size={18} className="text-green-500" />
                  ) : testResult === 'error' ? (
                    <AlertTriangle size={18} className="text-red-500" />
                  ) : (
                    <RefreshCw size={18} />
                  )}
                </button>
              )}
            </div>
          </div>
          
           {/* 提示信息 */}
          <div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
            <p className="text-xs text-gray-500">
              <span className="flex items-center mb-1">
                <ArrowLeft size={14} className="mr-1" />
                提示：
              </span>
              1. 您的API Key将安全地存储在本地浏览器中<br />
              2. 使用真实API模式可以获得更准确的故事生成结果<br />
             3. 模拟模式无需API Key，使用预设的故事模板<br />
4. 全局配置的API Key优先级高于本地存储的API Key<br />
5. 配置生效后，所有故事生成都将优先使用真实AI大模型
            </p>
          </div>
        </div>
        
        {/* 底部按钮 */}
        <div className="flex justify-end p-5 border-t border-pink-100 space-x-3">
          <button
            onClick={onClose}
            className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleSave}
            disabled={isSaving || (aiMode === 'real' && !apiKey.trim())}
            className={`px-4 py-2 rounded-lg transition-colors flex items-center ${
              isSaving || (aiMode === 'real' && !apiKey.trim())
                ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                : 'bg-gradient-to-r from-pink-500 to-blue-500 text-white hover:opacity-90'
            }`}
          >
            {isSaving ? (
              <>
                <RefreshCw size={16} className="mr-1.5 animate-spin" />
                保存中...
              </>
            ) : (
              <>
                <Save size={16} className="mr-1.5" />
                保存配置
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}